<?php

namespace App\Http\Controllers\API\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Dcat\Admin\Models\Administrator;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{

    public function login(Request $request)
    {
        $param = $request->all();

        $user = Administrator::where('username', $param['username'])->first();

        if (!$user) {
            return $this->failure('用户名或密码错误');
        }

        $password = $param['password'];

        if (!Hash::check($password, $user->password)) {
            return $this->failure('用户名或密码错误');
        }

        return $this->success($this->createTokenUser($user));
    }

    /**
     * 登录后返回
     * @param User $user
     * @return mixed
     */
    protected function createTokenUser(Administrator $user)
    {

        $success['token_type'] = 'Bearer';
        $success['token'] =  $user->createToken('MyApp')->accessToken;
        $success['username'] =  $user->username;
        $success['name'] =  $user->name;
        $success['user_id'] =  $user->id;
        $success['role_status'] = $user->roles[0]->id;

        return $success;
    }

    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $user = Auth::user();

        if (empty($user)) {
            return $this->apiReturn($user, '暂未登录', false);
        }

        // 获取当前登陆用户的token并且将其删除
        $token = Auth::guard('api')->user()->token();

        if (empty($token)) {
            return $this->failure('暂无有效令牌');
        }

        if (!empty($token->delete())) {
            return $this->success([], '退出成功');
        } else {
            return $this->failure('token删除失败');
        }
    }
}
